﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using NHibernate;
using NHibernate.Criterion;

namespace SmartProject.Entity
{
    public class Role : EntityBase
    {
        public Role()
        {
            Users = new List<User>();
            Permissions = new List<Permission>();
        }

        public virtual string Name { get; set; }

        public virtual IList<User> Users { get; set; }

        public virtual IList<Permission> Permissions { get; set; }

        /// <summary>
        /// This is a helper method to find the Id associated with this particular role name.
        /// </summary>
        /// <param name="roleName">Name of the role.</param>
        /// <returns>RoleName Id.</returns>
        public static Role GetRole(ISession session, string roleName)
        {
            IList<ICriterion> expressions = new List<ICriterion>();
            expressions.Add(Restrictions.Eq("Name", roleName));
            IList<EntityBase> entities = Find(session, expressions, null, typeof(Role));
            if (entities != null && entities.Count == 1)
            {
                return (Role)entities[0];
            }
            return null;
        }

        public virtual bool HasPermission(ISession session, string action)
        {
            for (int i = 0; i < this.Permissions.Count; i++)
            {
                if (this.Permissions[i].Action == action)
                {
                    return true;
                }
            }
            return false;
        }

        public static IList<Role> GetRoles(ISession session)
        {
            IList<EntityBase> entities = Find(session, null, null, typeof(Role));
            return (from p in entities select p as Role).ToList();
        }
    }
}
